<template>
	<div style="width: 100%">
		<div style="display: flex; align-items: center">
			<h3>课程安排</h3>
			<el-text v-if="!isRead" type="primary" style="margin-left: 20px; cursor: pointer" @click="modelShow = true">批量导入</el-text>
		</div>
		<el-table :data="courseList">
			<el-table-column type="index" label="序号" width="100px" :index="indexMethod" />

			<el-table-column label="课程顺序">
				<template #default="scope">{{ '第' + numberToChinese(scope.$index + 1) + '节课' }}</template>
			</el-table-column>
			<el-table-column prop="courseTitle" label="课程名称"></el-table-column>
			<el-table-column prop="signUpTime" label="课程时间">
				<template #default="{ row }"> {{ row.courseStartTime }}~{{ row.courseEndTime }} </template>
			</el-table-column>
			<el-table-column prop="courseLocation" label="课程地点"></el-table-column>
			<el-table-column prop="courseContent" label="课程介绍"> </el-table-column>
			<el-table-column label="操作">
				<template #default="{ row }">
					<el-text type="primary" style="cursor: pointer; margin-right: 20px" @click="openDetailShow(row)">详情</el-text>
					<el-text v-if="!isRead" type="primary" style="cursor: pointer; margin-right: 20px" @click="handleActive('edit', row)">编辑</el-text>
					<el-text v-if="!isRead" type="danger" style="cursor: pointer" @click="toDel(row)">删除</el-text>
				</template>
			</el-table-column>
		</el-table>
		<!-- 分页 -->
		<!-- <div class="right_part">
			<AplidPaginate v-bind="pageReac" @change="onPageChange" class="pageinate" />
		</div> -->
		<el-button v-if="!isRead" type="primary" style="width: 100%" @click="handleActive('add', {})"> +添加课程 </el-button>
		<!-- 详情 -->
		<AplidDialog title="详情" v-model="detailShow">
			<DetailPage ref="formRef1" v-bind="formConfig" :model="currentRow"> </DetailPage>
		</AplidDialog>
		<!-- 添加课程编辑-->
		<AplidDialog :title="activeType == 'add' ? '添加' : '编辑'" v-model="addEditShow">
			<AplidForm v-if="addEditShow" ref="formRef" v-bind="formConfig" v-model="formModel" @submit="onSubmit"> </AplidForm>
		</AplidDialog>
		<!-- 导入模版 -->
		<AplidDialog title="导入模版" v-model="modelShow">
			<el-text tag="ins" type="primary" style="cursor: pointer" @click="downloadTemplate">课程列表模版下载</el-text>
			<el-upload
				style="margin-top: 20px"
				ref="upload"
				drag
				:auto-upload="false"
				:on-change="uploadSuccess"
				:limit="1"
				accept=".xls,.xlsx"
				:on-exceed="handleExceed"
			>
				<el-icon size="100"><upload-filled /></el-icon>
				<div class="el-upload__text">将文件拖拽到这 或 <em>点击上传</em></div>
			</el-upload>
		</AplidDialog>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted } from 'vue'
import DetailPage from '@/views/aplid/DetailPage/index.vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { genFileId } from 'element-plus'
import apiMod from '@/apiMod/index'
import FileSaver from 'file-saver'
import ExcelJS from 'exceljs'
import { cloneDeep } from 'lodash-es'
// import { AplidPaginate } from '@/components/AplidCrud'

let props = defineProps({
	headId: {
		type: String,
		default: '',
	},
	signUpEndTime: {
		type: String,
		default: '',
	},
	isRead: {
		type: Boolean,
		default: false,
	},
})

let pageReac = ref({
	size: 1000,
	current: 1,
	total: 0,
})
let loading = ref(false)
let currentRow = ref({})
let detailShow = ref(false)
const openDetailShow = (row) => {
	let copyRow = cloneDeep(row)
	if (copyRow.courseStartTime && copyRow.courseEndTime) {
		copyRow.courseTime = copyRow.courseStartTime + '~' + copyRow.courseEndTime
	}
	currentRow.value = copyRow
	detailShow.value = true
}
let order = ref(0)
const indexMethod = (index: number) => {
	return index + 1
}
const numberToChinese = (num)=> {
      //  四位四位的进行分割
      const parts = num
        .toString()
        .replace(/(?=(\d{4})+$)/g, ',')
        .split(',')
        .filter(Boolean)
 
      const map = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
      const units = ['', '十', '百', '千']
      // 把连续的零给去掉 合并为1个零  当零在末尾的时候去掉
      function _handleZero(str) {
        return str.replace(/零+/g, '零').replace(/零$/, '')
      }
      function _transform(n) {
        let result = ''
        for (let i = 0; i < n.length; i++) {
          const c = map[n[i]]
          let u = units[n.length - i - 1]
          if (c === '零') {
            u = ''
          }
          result += c + u
        }
        result = _handleZero(result)
        return result
      }
      const bigUnits = ['', '万', '亿']
      let result = ''
      for (let i = 0; i < parts.length; i++) {
        const p = parts[i]
        const c = _transform(p)
        const u = bigUnits[parts.length - i - 1]
        if (c === '') {
          result += '零'
          continue
        }
        result += c + u
      }
      result = _handleZero(result)
      return result
    }

let modelShow = ref(false)
let formConfig = {
	stripe: true,
	border: true,
	maxHeight: '60vh',
	showBtn: true,
	showReset:false,
	column: [
		{
			label: '课程名称',
			prop: 'courseTitle',
			span: 12,
			rules: [{ required: true, message: '请填写课程名称' }],
		},
		{
			label: '课程时间',
			prop: 'courseTime',
			type: 'datetimerange',
			format: 'YYYY年MM月DD HH:mm:ss',
			valueFormat: 'YYYY-MM-DD HH:mm:ss',
			disabledDate: (date) => {
				// 控制课程时间
				return date.getTime() <= new Date(props.signUpEndTime)
			},
			span: 12,
			rules: [{ required: true, message: '请填写课程时间' }],
		},
		{
			label: '课程地点',
			prop: 'courseLocation',
			span: 12,
			rules: [{ required: true, message: '请填写课程地点' }],
		},
		{
			label: '课程介绍',
			prop: 'courseContent',
			span: 12,
			rules: [{ required: true, message: '请填写课程介绍' }],
		},
	],
}
let formModel = ref({})
let importCourseData = ref([])
// 获取所有课程
let courseList = ref([])
const getCourseList = () => {
	apiMod.view_bscTrainingCourse_list({ headId: props.headId, pageParaPO: pageReac.value }).then((res) => {
		if (res.code == 0) {
			if(res.data.length>0){
				order.value =  res.data[res.data.length-1].courseCode
			}
			pageReac.value.total = res.data.length
			courseList.value =  res.data
		}
	})
}
getCourseList()
const onPageChange = (data) => {
	pageReac.value = data
	getCourseList()
}
// 单个添加课程
const onSubmit = (form, done) => {
	let copyFrom = cloneDeep(form)
	if (copyFrom.courseTime.length > 0) {
		copyFrom.courseStartTime = copyFrom.courseTime[0]
		copyFrom.courseEndTime = copyFrom.courseTime[1]
		copyFrom.courseTime = undefined
	}
	copyFrom.signUpEndTime = props.signUpEndTime

	if (activeType.value == 'add') {
		copyFrom.courseCode = ++order.value
		copyFrom.headId = props.headId
		apiMod
			.view_bscTrainingCourse_add(copyFrom)
			.then((res) => {
				if (res.code == 0) {
					ElMessage.success('添加成功')
					// getCourseList()
					courseList.value.push(copyFrom)
					addEditShow.value = false
					done()
				} else {
					addEditShow.value = false
					done()
				}
			})
			.catch(() => {
				// 报错不关闭
				done()
			})
	} else {
		if (copyFrom.falseData) {
			// 假数据
			console.log('-=-1',courseList.value,copyFrom)
			let index = courseList.value.findIndex((item) => item.courseCode == copyFrom.courseCode)
			let index1 = importCourseData.value.findIndex((item) => item.courseCode == copyFrom.courseCode)
			courseList.value[index] = copyFrom
			importCourseData.value[index1] = copyFrom
			console.log('-=-2',courseList.value)
			ElMessage.success('编辑成功')
			addEditShow.value = false
		} else {
			apiMod
				.view_bscTrainingCourse_edit(copyFrom)
				.then((res) => {
					if (res.code == 0) {
						ElMessage.success('编辑成功')
						// getCourseList()
						let index = courseList.value.findIndex((item) => item.id == copyFrom.id)
						let index1 = importCourseData.value.findIndex((item) => item.courseCode == copyFrom.courseCode)
						importCourseData.value[index1] = copyFrom
						courseList.value[index] = copyFrom
						console.log('-=-',courseList.value)
						addEditShow.value = false
						done()
					} else {
						addEditShow.value = false
						done()
					}
				})
				.catch(() => {
					done()
				})
		}
	}
}
// 删除
const toDel = (row) => {
	// 确认删除吗
	ElMessageBox.confirm(`将删除当前${row.courseTitle}数据,确认?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			if (row.falseData) {
				courseList.value = courseList.value.filter((item) => item.courseCode !== row.courseCode)
				importCourseData.value = importCourseData.value.filter((item) => item.courseCode !== row.courseCode)
				console.log('fffg',courseList.value)
				ElMessage.success('删除成功')
				pageReac.value.total = courseList.value.length
			} else {
				apiMod.view_bscTrainingCourse_del([row.id]).then((res) => {
					if (res.code == 0) {
						ElMessage.success('删除成功')
						courseList.value = courseList.value.filter((item) => item.id !== row.id)
						// getCourseList()
					}
				})
			}
		})
		.catch(() => {})
}
let addEditShow = ref(false)
let activeType = ref('add')
const handleActive = (type, row) => {
	activeType.value = type
	// 处理一下时间
	let copy = cloneDeep(row)
	if (copy.courseStartTime && copy.courseEndTime) {
		copy.courseTime = [copy.courseStartTime, copy.courseEndTime]
	}
	formModel.value = copy || {}
	addEditShow.value = true
}

const importExcel = (files) => {
	return new Promise((resolve, reject) => {
		if (!files) {
			reject('文件不存在')
			return
		}
		const workbook = new ExcelJS.Workbook()
		const fileReader = new FileReader()
		fileReader.readAsArrayBuffer(files)
		fileReader.onload = (ev: any) => {
			workbook.xlsx
				.load(ev.target.result)
				.then((workbook: any) => {
					const wData = [...workbook._worksheets].filter(Boolean)
					let worksheet = workbook.getWorksheet(1)
					if (!worksheet) {
						worksheet = wData[0]
					}
					const headers = []
					worksheet.getRow(1).eachCell((cell) => {
						headers.push(cell.value)
					})
					const data = []
					for (let rowNumber = 2; rowNumber <= worksheet.rowCount; rowNumber++) {
						const rowData = {}
						const row = worksheet.getRow(rowNumber)
						row.eachCell((cell, colNumber) => {
							rowData[headers[colNumber - 1]] = cell.value
						})
						data.push(rowData)
					}
					resolve({
						data,
						headers,
					})
				})
				.catch((res) => {
					ElMessage.error('文件格式错误')
				})
		}
	})
}

// 上传,解析数据

const uploadSuccess = (files) => {
	console.log('fffdf',files)
	importExcel(files.raw).then((res: any) => {
		// 处理文件为对应格式
		let list = res.data.map((el, index) => {
			if(JSON.stringify(el)!='{}'&&el['*课程名称']){
				return {
					courseCode: ++order.value,
					headId: props.headId,
					signUpEndTime: props.signUpEndTime,
					courseTitle: el['*课程名称'],
					courseStartTime: el['* 课程开始时间(严格按照2022-01-02 00:00:00的格式录入)'],
					courseEndTime: el['* 课程结束时间(严格按照2022-01-02 00:00:00的格式录入)'],
					courseLocation: el['*课程地点'],
					courseContent: el['*课程介绍'],
					falseData: true,
				}
			}
		})
		// 判断是否合规定
		// 如果有已存在的课程那最后一条，那第一条数据一定要在结束时间后
		if(courseList.value.length>0){
			let preEndTime = new Date(courseList.value[courseList.value.length-1]['courseEndTime']).getTime()
			let newStartTime =  new Date(list[0]['courseStartTime']).getTime()
			if(preEndTime>newStartTime){
				ElMessage.error('课程开始时间必须迟于已存在课程的结束时间')
				return
			}
			
		}
		if(list&&list.length>1){
			let res1= list.every((el,index)=>{
				if(list[index+1]){
					let a = new Date(el['courseEndTime']).getTime()<new Date(list[index+1]['courseStartTime']).getTime()
					return a
				}else{
					return true
				}
			})
			// 时间排序不正确
			if(!res1){
				ElMessage.error('上一节课的结束时间必须早于下一节课的开始时间')
				return
			}
			let res2= list.every((el,index)=>{
				if(list[index+1]){
					let b = new Date(el['courseStartTime']).getTime()<new Date(list[index+1]['courseStartTime']).getTime()
					return b
				}else{
					return true
				}
			})
			// 时间排序不正确
			if(!res2){
				ElMessage.error('上一节课的开始时间必须早于下一节课的开始时间')
				return
			}
			let res3= list.every((el,index)=>{
				if(list[index+1]){
					let c = new Date(el['courseEndTime']).getTime()<new Date(list[index+1]['courseEndTime']).getTime()
					return c
				}else{
					return true
				}
			})
			// 时间排序不正确
			if(!res3){
				ElMessage.error('上一节课的结束时间必须早于下一节课的结束时间')
				return
			}
		}

		list = list.filter(Boolean)
		importCourseData.value = [...importCourseData.value, ...list]
		courseList.value = [...courseList.value, ...list]
		
		pageReac.value.total = courseList.value.length
		modelShow.value = false
	})
}
let upload = ref()
const handleExceed = (files) => {
	upload.value!.clearFiles()
	const file = files[0]
	file.uid = genFileId()
	upload.value!.handleStart(file)
}
// 下载模版
const downloadTemplate = () => {
	FileSaver.saveAs('https://aplid-51.oss-cn-hangzhou.aliyuncs.com/1719986838849_8c7c8ee3.xlsx', '课程安排.xlsx')
}
const getData = (fun) => {
	fun(importCourseData.value)
}
defineExpose({
	getData,
})
</script>
<style scoped lang="scss">
.btn_part {
	margin-top: 40px;
	width: 100%;
	display: flex;
	flex-direction: row;
	justify-content: center;
}
.right_part {
	display: flex;
	flex-direction: row-reverse;
	margin: 20px 0;
}
</style>
